package com.freek.ScreenDrop;

import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.prefs.Preferences;

import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import com.dropbox.client2.exception.DropboxException;

public class GlobalKeyListener implements NativeKeyListener
{
	public static KeyCombo desktopCombo = new KeyCombo(KeyEvent.VK_3,KeyEvent.CTRL_MASK|KeyEvent.SHIFT_MASK);
	public static KeyCombo windowCombo = new KeyCombo(KeyEvent.VK_2,KeyEvent.CTRL_MASK|KeyEvent.SHIFT_MASK);
	public static KeyCombo regionCombo = new KeyCombo(KeyEvent.VK_4,KeyEvent.CTRL_MASK|KeyEvent.SHIFT_MASK);
	
	public static void loadKeyCombos()
	{
		Preferences prefs = Preferences.userNodeForPackage(OptionsFrame.class);
		desktopCombo = KeyCombo.get(prefs, OptionsFrame.DESKTOP_COMBO, desktopCombo);
		windowCombo = KeyCombo.get(prefs, OptionsFrame.WINDOW_COMBO, windowCombo);
		regionCombo = KeyCombo.get(prefs, OptionsFrame.REGION_COMBO, regionCombo);
	}
	
	@Override
	public void nativeKeyPressed(NativeKeyEvent e)
	{
//		NativeKeyEvent.
		KeyCombo combo = new KeyCombo(e.getKeyCode(),e.getModifiers());
		if(desktopCombo.matches(combo))
		{
			try
			{
				Capture.desktop();
			} catch (IOException | AWTException | DropboxException | URISyntaxException e1)
			{
				e1.printStackTrace();
			}
		}
		if(windowCombo.matches(combo))
		{
			try
			{
				Capture.window();
			} catch (IOException e1)
			{
				e1.printStackTrace();
			}
		}
		if(regionCombo.matches(combo))
		{
				final RegionSelectFrame frame = RegionSelectFrame.selectRegion();
				frame.requestFocus();
				frame.toFront();
				frame.addWindowListener(new WindowAdapter() {
					public void windowClosed(WindowEvent e) {
						try
						{
							if(frame.region != null)
								Capture.region(RegionSelectFrame.absRect(frame.region));
						} catch (IOException | AWTException e1)
						{
							e1.printStackTrace();
						}
					};
				});
		}
	}

	@Override
	public void nativeKeyReleased(NativeKeyEvent e)
	{

	}

	@Override
	public void nativeKeyTyped(NativeKeyEvent e)
	{
	}

}
